<script setup>
import { ref, onMounted } from 'vue'
import { ElDialog } from 'element-plus'

const props = defineProps({
  file: {
    type: Object,
    required: true
  },
  selected: {
    type: Boolean,
    default: false
  }
})

// 缩略图状态
const thumbnail = ref(null)
const loading = ref(false)
const error = ref(false)

// 获取媒体URL
const getMediaUrl = (path) => {
  console.log('getMediaUrl:', path)
  if (!path) return ''
  
  // 对于缩略图，使用 media:// 协议
  const normalizedPath = path.replace(/\\/g, '/')
  const cleanPath = normalizedPath.replace(/^\/+/, '')
  return `media://${cleanPath}`
}

// 处理图片加载错误
const handleImageError = (e) => {
  const imgSrc = e.target.src
  console.error('Image load error:', {
    src: imgSrc,
    file: props.file.path,
    thumbnail: thumbnail.value
  })
  error.value = true
}

// 生成缩略图
const generateThumbnail = async () => {
  if (props.file.type !== 'video' || loading.value) return
  
  loading.value = true
  error.value = false
  
  try {
    console.log('Requesting thumbnail for video:', {
      path: props.file.path,
      name: props.file.name
    })

    const result = await window.mediaManager.generateThumbnail(props.file.path)
    
    console.log('Thumbnail generation result:', {
      success: !!result,
      thumbnailPath: result,
      videoPath: props.file.path,
      videoName: props.file.name
    })
    
    if (result) {
      thumbnail.value = result
      // 移除文件检查，直接使用路径
    } else {
      error.value = true
      console.error('No thumbnail generated')
    }
  } catch (err) {
    console.error('Thumbnail generation failed:', {
      error: err,
      videoPath: props.file.path
    })
    error.value = true
  } finally {
    loading.value = false
  }
}

// 在组件挂载时生成缩略图
onMounted(async () => {
  if (props.file.type === 'video') {
    await generateThumbnail()
  }
})

// 添加事件处理
const emit = defineEmits(['click', 'media-event'])

const handleClick = (e) => {
  e.preventDefault()
  e.stopPropagation()
  emit('click', e)
}

// 修改视频点击处理
const handleVideoClick = (e) => {
  e.stopPropagation() // 阻止事件冒泡，避免触发选择
  if (props.file.type === 'video') {
    emit('media-event', 'play-video', props.file)
  }
}
</script>

<template>
  <div 
    class="media-item"
    :class="{ selected }"
    :data-path="file.path"
    @click="handleClick"
  >
    <!-- 选中指示器 -->
    <div class="select-indicator" v-if="selected">
      <el-icon><Check /></el-icon>
    </div>

    <!-- 媒体预览容器 -->
    <div class="media-preview-container">
      <!-- 媒体预览 -->
      <div class="media-preview">
        <!-- 图片文件 -->
        <img
          v-if="file.type === 'image'"
          :src="getMediaUrl(file.path)"
          :alt="file.name"
          @error="handleImageError"
        />
        <!-- 视频文件 -->
        <div v-else-if="file.type === 'video'" class="video-preview">
          <template v-if="thumbnail && !error">
            <img
              :src="getMediaUrl(thumbnail)"
              :alt="file.name"
              @error="handleImageError"
              @load="() => { error = false }"
            />
          </template>
          <div v-else class="video-placeholder" :class="{ loading }">
            <el-icon><VideoCamera /></el-icon>
            <span v-if="error" class="error-text">预览图加载失败</span>
          </div>
          <div class="video-badge" @click="handleVideoClick">
            <el-icon><VideoPlay /></el-icon>
          </div>
        </div>
      </div>
    </div>

    <!-- 文件信息 -->
    <div class="media-info">
      <span class="file-name">{{ file.name }}</span>
    </div>
  </div>
</template>

<style scoped>
.media-item {
  position: relative;
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  user-select: none; /* 防止文本选择 */
  touch-action: none; /* 优化触摸设备上的操作 */
}

.media-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.media-item.selected {
  border: 2px solid var(--el-color-primary);
}

.select-indicator {
  position: absolute;
  top: 8px;
  left: 8px;
  z-index: 2;
  width: 24px;
  height: 24px;
  background: var(--el-color-primary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

/* 预览容器，固定宽高比 */
.media-preview-container {
  position: relative;
  width: 100%;
  padding-top: 100%; /* 1:1 的容器，仅用于小图和中图模式 */
  overflow: hidden;
}

.media-preview {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}

.media-preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  margin: auto;
}

.video-preview {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  margin: auto;
}

.video-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 32px;
  background: #f5f7fa;
  gap: 8px;
}

.video-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 36px;
  height: 36px;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  transition: all 0.3s ease;
  /* z-index: 1; */
  aspect-ratio: 1;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.video-badge:hover {
  background: rgba(0, 0, 0, 0.7);
  transform: scale(1.08);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.video-badge .el-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0.9;
}

.video-badge:hover .el-icon {
  opacity: 1;
}

/* 视频播放器样式 */
.video-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #000;
  border-radius: 4px;
  overflow: hidden;
}

.video-player {
  width: 100%;
  max-height: 80vh;
  object-fit: contain;
}

.media-info {
  padding: 8px;
  flex-shrink: 0;
}

.file-name {
  display: block;
  font-size: 13px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.error-text {
  font-size: 12px;
  color: #f56c6c;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

/* 大图模式下的特殊处理 */
:deep(.large-grid) {
  .media-preview,
  .video-preview {
    position: relative;
    height: 100%;
  }

  .media-preview img,
  .video-preview img {
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
  }
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-dialog__header) {
  padding: 12px 20px;
  margin: 0;
  border-bottom: 1px solid #eee;
}
</style> 